<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="90px">
      <el-row>

        <el-form-item label="短信平台" prop="smsPlatform">
          <el-select v-model="queryParams.smsPlatform" placeholder="请选择短信平台" clearable size="small">
            <el-option v-for="dict in smsPlatformType" :key="dict.value" :label="dict.value" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="短信签名" prop="sign">
          <el-input v-model="queryParams.sign" placeholder="请输入短信签名" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="dataStatus">
          <el-select v-model="queryParams.dataStatus" placeholder="请选择状态" clearable size="small">
            <el-option v-for="dict in dataStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>
    </el-form>

    <el-row :gutter="10" class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['platform:config:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['platform:config:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="divTable">
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="短信平台" align="center" prop="smsPlatform" :show-overflow-tooltip="true" />
        <el-table-column label="短信模板ID" align="center" prop="templateId" :show-overflow-tooltip="true" />
        <el-table-column label="短信签名" align="center" prop="sign" :show-overflow-tooltip="true" />
        <el-table-column label="秘钥ID" align="center" prop="secretId" :show-overflow-tooltip="true" />
        <el-table-column label="秘钥KEY" align="center" prop="secretKey" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="dataStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="短信类型" align="center" prop="smsType" :formatter="smsTypeFormat" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:config:edit']">修改</el-button>
            <el-button v-if="scope.row.dataStatus == 0" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['platform:config:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改短信配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="短信平台" prop="smsPlatform">
              <el-select v-model="form.smsPlatform" placeholder="请选择短信平台" clearable size="small">
                <el-option v-for="dict in smsPlatformType" :key="dict.value" :label="dict.value" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="appID" prop="smsSdkAppid">
              <el-input v-model="form.smsSdkAppid" placeholder="请输入appID" class="select-normal" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="短信模板ID" prop="templateId">
              <el-input v-model="form.templateId" placeholder="请输入短信模板ID" class="select-normal" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="短信签名" prop="sign">
              <el-input v-model="form.sign" placeholder="请输入短信签名" class="select-normal" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="秘钥ID" prop="secretId">
              <el-input v-model="form.secretId" placeholder="请输入秘钥ID" class="select-normal" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="秘钥KEY" prop="secretKey">
              <el-input v-model="form.secretKey" placeholder="请输入秘钥KEY" class="select-normal" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="短信类型" prop="smsType">
              <el-select v-model="form.smsType" placeholder="请选择短信类型" class="select-normal">
                <el-option v-for="dict in smsTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看短信配置对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-form ref="detailForm" label-width="100px">
        <el-row>
          <el-col :span="12" v-for="(item, index) in showData" :key="index" style="margin-top:-15px">
            <el-form-item :label="`${item.label}：`">
              <span>{{item.value}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listConfig,
    getConfig,
    delConfig,
    addConfig,
    updateConfig,
    updateConfigStatus
  } from "@/api/platform/config";

  export default {
    name: "Config",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        smsPlatformType: [{
          value: "腾讯"
        }, {
          value: "阿里"
        }],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 短信配置表格数据
        configList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: [],
        // 数据状态，1有效，0无效字典
        dataStatusOptions: [],
        // 短信类型，验证码(code)/通知(notice)字典
        smsTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          platformId: null,
          smsPlatform: null,
          smsSdkAppid: null,
          templateId: null,
          sign: null,
          secretId: null,
          secretKey: null,
          createUid: null,
          createName: null,
          updateUid: null,
          updateName: null,
          dataStatus: null,
          smsType: null
        },
        columns: [{
            label: '短信类型，验证码(code)/通知(notice)',
            dataIndex: 'configId',
          },
          {
            label: '平台ID',
            dataIndex: 'platformId',
          },
          {
            label: '短信平台 腾讯/阿里',
            dataIndex: 'smsPlatform',
          },
          {
            label: 'appID',
            dataIndex: 'smsSdkAppid',
          },
          {
            label: '短信模板ID',
            dataIndex: 'templateId',
          },
          {
            label: '短信签名',
            dataIndex: 'sign',
          },
          {
            label: '秘钥ID',
            dataIndex: 'secretId',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'secretKey',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'createUid',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'createName',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'createTime',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'updateUid',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'updateName',
          },
          {
            label: '秘钥KEY',
            dataIndex: 'updateTime',
          },
          {
            label: '数据状态，1有效，0无效',
            dataIndex: 'dataStatus',
          },
          {
            label: '短信类型，验证码(code)/通知(notice)',
            dataIndex: 'smsType',
          },
        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          smsPlatform: [{
            required: true,
            message: "短信平台不能为空",
            trigger: "blur"
          }],
          smsSdkAppid: [{
            required: true,
            message: "appid不能为空",
            trigger: "blur"
          }],
          templateId: [{
            required: true,
            message: "短信模板id不能为空",
            trigger: "blur"
          }],

        }
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_data_status").then(response => {
        this.dataStatusOptions = response.data;
      });
      this.getDicts("platform_sms_type").then(response => {
        this.smsTypeOptions = response.data;
      });
    },
    methods: {
      /** 查询短信配置列表 */
      getList() {
        this.loading = true;
        listConfig(this.queryParams).then(response => {
          this.configList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 数据状态，1有效，0无效字典翻译
      dataStatusFormat(row, column) {
        return this.selectDictLabel(this.dataStatusOptions, row.dataStatus);
      },
      // 短信类型，验证码(code)/通知(notice)字典翻译
      smsTypeFormat(row, column) {
        return this.selectDictLabel(this.smsTypeOptions, row.smsType);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          configId: null,
          platformId: null,
          smsPlatform: null,
          smsSdkAppid: null,
          templateId: null,
          sign: null,
          secretId: null,
          secretKey: null,
          createUid: null,
          createName: null,
          createTime: null,
          updateUid: null,
          updateName: null,
          updateTime: null,
          dataStatus: null,
          smsType: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.configId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.dataStatus) {
              this.multiple = true;
              break;
            }
          }
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加短信配置";
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.viewOpen = true;
        this.viewTitle = "查看短信配置";
        this.showData = [];
        this.columns.forEach(item => {
          this.showData.push({
            label: item.label,
            value: row[item.dataIndex]
          })
        })
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const configId = row.configId || this.ids
        getConfig(configId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改短信配置";
        });
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        this.$confirm('确定要把短信签名为"' + row.single + '",设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateConfigStatus(row.brandUid, row.dataStatus);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.configId != null) {
              updateConfig(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addConfig(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const configIds = row.configId || this.ids;
        this.$confirm('是否确认删除短信配置编号为"' + configIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delConfig(configIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('platform/config/export', {
          ...this.queryParams
        }, `platform_config.xlsx`)
      }
    }
  };
</script>
